﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleX.Tracing
{
    public class TracingService : ITracingService
    {
        private readonly ITraceIdManager _traceIdManager;
        private readonly ILogger<TracingService> _logger;
        private readonly ActivitySource _activitySource;

        public TracingService(
            ITraceIdManager traceIdManager,
            ILogger<TracingService> logger,
            ActivitySource activitySource)
        {
            _traceIdManager = traceIdManager;
            _logger = logger;
            _activitySource = activitySource;
        }

        public string CurrentTraceId => _traceIdManager.GetTraceId();

        public void AddCustomProperty(string key, object value)
        {
            var activity = Activity.Current;
            if (activity != null)
                activity.SetTag(key, value);
        }

        public void LogEvent(string eventName, params (string Key, object Value)[] properties)
        {
            using var activity = _activitySource.StartActivity(eventName, ActivityKind.Internal);

            if (properties != null)
            {
                foreach (var (key, value) in properties)
                {
                    activity?.SetTag(key, value);
                }
            }

            _logger.LogInformation("Event: {EventName} [TraceId: {TraceId}]",
                eventName,
                CurrentTraceId);
        }

        public void LogException(Exception exception, string message = null)
        {
            using var activity = _activitySource.StartActivity("Exception", ActivityKind.Internal);

            _logger.LogError(exception,
                "Exception: {Message} [TraceId: {TraceId}]",
                message ?? exception.Message,
                CurrentTraceId);
        }
    }
}